/**
 * 
 */
(function() {
	/***************************************************************************
	 * 页面初始化
	 */
	// $(document).keydown(function(event) {
	// platform.forbiddenEnter(event);
	// });
	window.onload = function() {
		treeView.loadTree();
		menuGridView.init();
    };

	/***************************************************************************
	 * 左侧菜单树
	 */
	var treeView = {
		loadTree : function() {
			var nodes = methods.loadTreeNodes();
			platform.removeEmptyNode(nodes);

			var $el = $("#treeView").treeview({
				data : nodes,
				highlightSelected : true,
				selectedBackColor : "RGB(245,245,245)",
				selectedColor : "RGB(51,51,51)",
				emptyIcon : "",
				levels : 0
			});
			$el.on('nodeSelected', function(event, data) {
				$("#tb_menus").bootstrapTable("refresh", {
					query : {
						p_menu_id : data.id
					}
				});
			});
		}
    };
	ko.applyBindings(treeView, document.getElementById('treeView'));
	/***************************************************************************
	 * GridView
	 */
	var menuGridView = {
		/**
		 * method
		 */
		/**
		 * 初始化
		 */
		init : function() {
			var columns = [ {
				checkbox : true,
				field : 'checkbox',
			}, {
				field : 'menu_id',
				title : '主键标识',
				visible : false
			}, {
				field : 'menu_name',
				title : '菜单名称'
			}, {
				field : 'menu_code',
				title : '快速启动编码'
			}, {
				field : 'menu_uri',
				title : '链接地址'
			}, {
				field : 'icon_cls',
				title : '菜单图标',
				formatter : function(value, row, index) {
					return "<i class='" + value + "'></i>";
				}
			} ];
			$('#tb_menus').bootstrapTable({
				url : platform.mapUrl('~/rest/menu/list'),
				cache : false,
				method : 'post',
				contentType : 'application/json',
				dataType : 'json',
				search : false,
				strictSearch : true,
				singleSelect : true,
				striped : true,
				showFooter : false,
				showToggle : false,
				showRefresh : true,
				showPaginationSwitch : false,
				silent : true,
				pagination : true,
				sidePagination : 'server',
				pageNumber : 1,
				pageSize : 10,
				pageList : [ 10, 15, 20, 50 ],
				queryParams : function(params) {
					return {
						pageNumber : params.offset / params.limit + 1,
						pageSize : params.limit,
						p_menu_id : ''
					}
				},
				clickToSelect : true,
				height : 504,
				uniqueId : 'menu_id',
				detailView : false,
				cardView : false,
				toolbar : '#toolbar',
				columns : columns
			});
		},
		fnSearch : function() {
			$(this.$table).bootstrapTable('refresh', {
				query : {

				}
			});
		},
		fnAdd : function() {
			var selectedNode = $('#treeView').treeview(true).getSelected();
			if (selectedNode == undefined || selectedNode.length == 0) {
				platform.confirm('系统提示', 'small', '确认是否新增顶级菜单?', '确认', '取消',
						function() {
							menuView.showNewForm();
						});
			} else {
				menuView.showNewForm(selectedNode[0].id);
			}
		},
		fnRemove : function() {
			var selections = $('#tb_menus').bootstrapTable('getSelections');
			if (selections == null || selections == undefined
					|| (selections instanceof Array && selections.length != 1)) {
				platform.showtip('remove');
				return;
			}
			bootbox.confirm({
				title : '<i class="fa fa-warning"></i>&nbsp;&nbsp;删除提示信息',
				size : 'small',
				message : '删除存在子节点的数据时，将删除全部该节点下的数据，确认是否删除?',
				buttons : {
					confirm : {
						label : '确认',
						className : 'btn-success btn-sm'
					},
					cancel : {
						label : '取消',
						className : 'btn-default btn-sm'
					}
				},
				callback : function(result) {
					// if(result) {
					// fnOk != undefined ? fnOk() : function() {};
					// } else {
					// fnCancel == undefined ? function() {} : fnCancel();
					// }
					var menu_id = selections[0].menu_id;
					methods.del(menu_id);
				}
			});
			// platform.confirm('<i class="fa
			// fa-warning"></i>&nbsp;&nbsp;删除提示信息',
			// 'small', '删除存在子节点的数据时，将删除全部该节点下的数据，确认是否删除?', '确认', '取消',
			// function() {
			// var menu_id = selections[0].menu_id;
			// methods.del(menu_id);
			// });
		},
		fnEdit : function() {
			var result = platform.checkSelected('tb_menus', 'EDIT');
			if (result) {
				var selections = $('#tb_menus').bootstrapTable('getSelections');
				menuView.showEditForm(selections[0].menu_id);
			}
		},
		fnView : function() {
			var result = platform.checkSelected('tb_menus', 'VIEW');
			if (result) {
				var selections = $('#tb_menus').bootstrapTable('getSelections');
				menuView.showViewForm(selections[0].menu_id);
			}
		},
		fnMove : function() {// 移动菜单至指定节点下
			var result = platform.checkSelected('tb_menus', 'move');
			if (result) {
				treeModel.showModal();
			}
		},
		refreshTable : function() {
			$('#tb_menus').bootstrapTable('refresh');
		}
    };
	ko.applyBindings(menuGridView, document.getElementById('menuList'));
	/***************************************************************************
	 * menuViewHeader
	 */
	var menuViewHeader = {
		mv_title : ko.observable()
    };
	ko.applyBindings(menuViewHeader, document.getElementById('modalHeader'));
	/***************************************************************************
	 * menuView
	 */
	var menuView = {
		/**
		 * parameter
		 */
		mv_menuid : ko.observable(),// 菜单主键
		mv_menucode : ko.observable(),
		mv_menuname : ko.observable(),
		mv_menuuri : ko.observable(),
		mv_pmenuid : ko.observable(),
		mv_iconcls : ko.observable(),
		mv_editstatus : ko.observable(),// 默认数据状态
		mv_recordstatus : ko.observable(),// 默认数据状态
		mv_enabled : ko.observable(false),// 只读设置
		/**
		 * method
		 */
		initForm : function() {
			this.mv_menuid(platform.uuid());
			this.mv_editstatus('0');
			this.mv_recordstatus('1');
			this.mv_enabled(true);
		},
		clear : function() {
			this.mv_menuid('');
			this.mv_menucode('');
			this.mv_menuname('');
			this.mv_menuuri('');
			this.mv_pmenuid('');
			this.mv_iconcls('');
			this.mv_editstatus('');
			this.mv_recordstatus('');
			this.mv_enabled(false);
		},
		validateForm : function() {
			$('#detailForm').bootstrapValidator({
				message : 'This value is not valid',
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				excluded : [ ':disabled' ],
				fields : {
					menuName : {
						validators : {
							notEmpty : {
								message : '菜单名称为必填字段,不可为空'
							}
						}
					}
				}
			});
		},
		resetForm : function() {
			if ($('#detailForm').data('bootstrapValidator') != null
					|| $('#detailForm').data('bootstrapValidator') != undefined) {
				$('#detailForm').data('bootstrapValidator').resetForm();
			}
		},
		showNewForm : function(str) {
			menuViewHeader.mv_title('菜单信息录入');
			this.clear();
			this.initForm();
			if (str != undefined) {
				this.mv_pmenuid(str);
			}
			this.validateForm();
			$('#menuModal').modal('show');
		},
		showEditForm : function(pid) {

			var result = methods.get(pid);
			// var form = this;
			this.clear();
			this.validateForm();
			this.mv_menuid(pid);
			this.mv_menucode(result.menu_code);
			this.mv_menuname(result.menu_name);
			this.mv_menuuri(result.menu_uri);
			this.mv_iconcls(result.icon_cls);
			this.mv_editstatus('1');// 编辑状态
			this.mv_enabled(true);
			menuViewHeader.mv_title('菜单信息编辑');

			$('#menuModal').modal('show');
		},
		showViewForm : function(pid) {
			var result = methods.get(pid);
			var form = menuView;
			form.clear();
			form.resetForm();
			form.mv_menuid(pid);
			form.mv_menucode(result.menu_code);
			form.mv_menuname(result.menu_name);
			form.mv_menuuri(result.menu_uri);
			form.mv_iconcls(result.icon_cls);
			form.mv_editstatus('2');// 编辑状态
			form.mv_enabled(false);
			menuViewHeader.mv_title('菜单信息查看');
			$('#saveBtn').hide();
			$('#menuModal').modal('show');
		}
    };
	ko.applyBindings(menuView, document.getElementById('detailForm'));
	/***************************************************************************
	 * MenuFunctionView
	 */
	var MenuFunctionView = {
		fnSaveForm : function() {
			$('#detailForm').data('bootstrapValidator').validate();
			if (!$('#detailForm').data('bootstrapValidator').isValid()) {
				platform.showOperTip('VALIDATEFAIL');
				return;
			}
			var form = menuView;
			var param = {};
			param.menu_id = form.mv_menuid();
			param.menu_code = form.mv_menucode();
			param.menu_name = form.mv_menuname();
			param.menu_uri = form.mv_menuuri();

			param.icon_cls = form.mv_iconcls();
			param.edit_status = form.mv_editstatus();
			if (param.edit_status == '0') {
				param.p_menu_id = form.mv_pmenuid();
				param.record_status = form.mv_recordstatus();
			}
			methods.save(param);
		},
		fnCloseDlg : function() {
			menuView.resetForm();
			$('input', 'form').attr('readonly');
			$('#menuModal').on('hidden.bs.modal', function() {
				$('#saveBtn').show();
			}).modal('hide');
		}
    };
	ko.applyBindings(MenuFunctionView, document.getElementById('modalFooter'));
	/***************************************************************************
	 * treeModel
	 */
	var treeModel = {
		mttitle : ko.observable(),
		init : function() {
			this.mttitle('菜单树选择');
			var nodes = methods.loadTreeNodes();
			platform.removeEmptyNode(nodes);
			$("#targetTree").treeview({
				data : nodes,
				highlightSelected : true,
				selectable : true,
				emptyIcon : ""
			});
		},
		showModal : function(menuid) {
			this.init();
			$('#treeModal').modal('show');
		},
		fnConfirmMove : function() {
			var selectedNode = $('#targetTree').treeview(true).getSelected();
			var selections = $('#tb_menus').bootstrapTable('getSelections');
			var param = {};
			param.menu_id = selections[0].menu_id;
			if (selectedNode.length == 0) {
				platform.confirm(
						'<i class="fa fa-warning"></i>&nbsp;&nbsp;提示信息',
						'small', '未选择父级节点,确认是否将数据变更为根级节点?', '确认', '取消',
						function() {
							methods.updateMenu(param);
							this.fnCancel();
						});
			} else {
				param.p_menu_id = selectedNode[0].id;
				if (param.menu_id == param.p_menu_id) {
					platform.showWarnTip('禁止将选择节点迁移至自节点下');
					return;
				}
				this.updateMenu(param);
				this.fnCancel();
			}
		},
		fnCancel : function() {
			$('#treeModal').modal('hide');
		}
    };
	ko.applyBindings(treeModel, document.getElementById('treeModal'));
	/***************************************************************************
	 * 基础方法
	 */
	var methods = {
		del : function(pid) {
			var param = {};
			param.menu_id = pid;
			platform.servicebreakAsync('~/rest/menu/delete', param, 'post')
					.done(function(response) {
						if (response.success) {
							platform.showOperTip('DELSUC');
							menuGridView.refreshTable();
							treeView.loadTree();

                        } else {
							platform.showErrorTip(response.msg);

                        }
					});
		},
		save : function(param) {
			platform.servicebreakAsync('~/rest/menu/save', param, 'post',
					function() {
						platform.showOperTip('dealing');
					}).done(function() {
				platform.showOperTip('savesuc');
				treeView.loadTree();
				menuGridView.refreshTable();
			});
		},
		get : function(pid) {
			var param = {};
			param.menu_id = pid;
			var result = JSON2.parse(platform.servicebreak(
					'~/rest/menu/selectOne', param).responseText).result;
			return result;
		},
		loadTreeNodes : function() {
			var nodes = JSON2.parse(platform
					.servicebreak('~/rest/menu/selectAll').responseText);
			return nodes;
		},
		updateMenu : function(param) {
			platform.servicebreakAsync('~/rest/menu/changeMenuPid', param,
					'post', function() {
						platform.showOperTip('dealing');
					}).done(function() {
				platform.showOperTip('savesuc');
				treeView.loadTree();
				menuGridView.refreshTable();
			});
		}
	}
})(this);